package com.ruoyi.airsystem.controller;

import java.util.Collections;
import java.util.List;
import javax.servlet.http.HttpServletResponse;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.airsystem.domain.AirRooms;
import com.ruoyi.airsystem.domain.AirFamilies;
import com.ruoyi.airsystem.service.IAirRoomsService;
import com.ruoyi.airsystem.service.IAirFamiliesService;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

@RestController
@RequestMapping("/airsystem/rooms")
public class AirRoomsController extends BaseController {

    @Autowired
    private IAirRoomsService airRoomsService;

    @Autowired
    private IAirFamiliesService airFamiliesService;

    /**
     * 查询房间管理列表
     */
    @PreAuthorize("@ss.hasPermi('airsystem:rooms:list')")
    @GetMapping("/list")
    public TableDataInfo list(AirRooms airRooms) {
        Long userId = SecurityUtils.getUserId();

        if (userId != 1L) {
            // 查询用户关联的家庭
            AirFamilies familyQuery = new AirFamilies();
            familyQuery.setUserId(userId);
            List<AirFamilies> families = airFamiliesService.selectAirFamiliesList(familyQuery);

            if (families.isEmpty()) {
                return getDataTable(Collections.emptyList()); // 替换为 Collections.emptyList()
            }
            // 设置房间查询的家庭ID条件
            airRooms.setFamilyId(families.get(0).getFamilyId()); // 假设一个用户只关联一个家庭
        }
        startPage();
        List<AirRooms> list = airRoomsService.selectAirRoomsList(airRooms);
        return getDataTable(list);
    }

    /**
     * 导出房间管理列表
     */
    @PreAuthorize("@ss.hasPermi('airsystem:rooms:export')")
    @Log(title = "房间管理", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, AirRooms airRooms) {
        Long userId = SecurityUtils.getUserId();

        if (userId != 1L) {
            AirFamilies familyQuery = new AirFamilies();
            familyQuery.setUserId(userId);
            List<AirFamilies> families = airFamiliesService.selectAirFamiliesList(familyQuery);

            if (!families.isEmpty()) {
                airRooms.setFamilyId(families.get(0).getFamilyId());
            } else {
                // 替换 List.of() 为 Collections.emptyList()
                ExcelUtil<AirRooms> util = new ExcelUtil<>(AirRooms.class);
                util.exportExcel(response, Collections.emptyList(), "房间管理数据");
                return;
            }
        }

        List<AirRooms> list = airRoomsService.selectAirRoomsList(airRooms);
        ExcelUtil<AirRooms> util = new ExcelUtil<>(AirRooms.class);
        util.exportExcel(response, list, "房间管理数据");
    }

    /**
     * 获取房间详细信息
     */
    @PreAuthorize("@ss.hasPermi('airsystem:rooms:query')")
    @GetMapping("/{roomId}")
    public AjaxResult getInfo(@PathVariable Long roomId) {
        AirRooms airRoom = airRoomsService.selectAirRoomsByRoomId(roomId);
        Long userId = SecurityUtils.getUserId();

        if (userId != 1L) {
            if (airRoom == null) {
                return AjaxResult.error("房间不存在");
            }

            // 验证房间是否属于用户关联的家庭
            AirFamilies familyQuery = new AirFamilies();
            familyQuery.setFamilyId(airRoom.getFamilyId());
            familyQuery.setUserId(userId);
            List<AirFamilies> families = airFamiliesService.selectAirFamiliesList(familyQuery);

            if (families.isEmpty()) {
                return AjaxResult.error("没有权限查看此房间");
            }
        }

        return success(airRoom);
    }

    /**
     * 新增房间
     */
    @PreAuthorize("@ss.hasPermi('airsystem:rooms:add')")
    @Log(title = "房间管理", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody AirRooms airRooms) {
        Long userId = SecurityUtils.getUserId();

        if (userId != 1L) {
            // 验证用户是否有权限在指定家庭下添加房间
            AirFamilies familyQuery = new AirFamilies();
            familyQuery.setFamilyId(airRooms.getFamilyId());
            familyQuery.setUserId(userId);
            List<AirFamilies> families = airFamiliesService.selectAirFamiliesList(familyQuery);

            if (families.isEmpty()) {
                return AjaxResult.error("没有权限在此家庭下添加房间");
            }
        }

        return toAjax(airRoomsService.insertAirRooms(airRooms));
    }

    /**
     * 修改房间
     */
    @PreAuthorize("@ss.hasPermi('airsystem:rooms:edit')")
    @Log(title = "房间管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody AirRooms airRooms) {
        Long userId = SecurityUtils.getUserId();

        if (userId != 1L) {
            AirRooms existing = airRoomsService.selectAirRoomsByRoomId(airRooms.getRoomId());
            if (existing == null) {
                return AjaxResult.error("房间不存在");
            }

            // 验证房间是否属于用户关联的家庭
            AirFamilies familyQuery = new AirFamilies();
            familyQuery.setFamilyId(existing.getFamilyId());
            familyQuery.setUserId(userId);
            List<AirFamilies> families = airFamiliesService.selectAirFamiliesList(familyQuery);

            if (families.isEmpty()) {
                return AjaxResult.error("没有权限修改此房间");
            }

            // 防止修改家庭ID
            airRooms.setFamilyId(existing.getFamilyId());
        }

        return toAjax(airRoomsService.updateAirRooms(airRooms));
    }

    /**
     * 删除房间
     */
    @PreAuthorize("@ss.hasPermi('airsystem:rooms:remove')")
    @Log(title = "房间管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/{roomIds}")
    public AjaxResult remove(@PathVariable Long[] roomIds) {
        Long userId = SecurityUtils.getUserId();

        if (userId != 1L) {
            for (Long roomId : roomIds) {
                AirRooms existing = airRoomsService.selectAirRoomsByRoomId(roomId);
                if (existing == null) {
                    return AjaxResult.error("房间ID为 " + roomId + " 的记录不存在");
                }

                // 验证房间是否属于用户关联的家庭
                AirFamilies familyQuery = new AirFamilies();
                familyQuery.setFamilyId(existing.getFamilyId());
                familyQuery.setUserId(userId);
                List<AirFamilies> families = airFamiliesService.selectAirFamiliesList(familyQuery);

                if (families.isEmpty()) {
                    return AjaxResult.error("没有权限删除房间ID为 " + roomId + " 的记录");
                }
            }
        }

        return toAjax(airRoomsService.deleteAirRoomsByRoomIds(roomIds));
    }
}
